<?php

namespace app\http\middleware;

use app\models\{Agent as model, Systemlog};

use think\Db;

class Agent
{
    public function handle($request, \Closure $next)
    {
        $id = session('agent_id');
        $agent = (new model())->where('id', $id)->find();
        $url = $request->baseUrl();
        if (!$agent && $url != '/index/login') {
            return redirect('/index/login');
        }
        if ($agent && $url == '/') {
            return redirect('/main/index');
        }
        if ($agent['status'] == 2) {
            session('agent_id', null);
            return redirect('/index/login');
        }
        $request->agent = $agent;
        if ($request->isAjax() && request()->controller(true) != 'base' && request()->method() != 'GET') {
            $array = [
                'module'        => 'agent',
                'controller'    => request()->controller(true),
                'action'        => request()->action(true),
                'params'        => serialize(request()->param()),
                'method'        => request()->method(),
                'url'           => request()->baseUrl(),
                'ip'            => request()->ip(),
                'name'          => $agent['accounts'] ?? '',
            ];
            if (empty($array['name'])) {
                $array['name'] = 'agent';
            }
            $array['type'] = 1;
            Systemlog::write($array);
        }
        return $next($request);
    }
}
